//
//  UIView+Tap.m
//  LZNeiHan
//
//  Created by 梁梓烽 on 16/10/1.
//  Copyright © 2016年 liangzifeng. All rights reserved.
//

#import "UIView+Tap.h"

static const char * ActionHandlerTapGestureKey;
@implementation UIView (Tap)

/** 动态地给view添加tap 手势 */
-(void)setTapActionWithBlock:(void(^)(void))block
{
    self.userInteractionEnabled =YES;
    
    UITapGestureRecognizer *gesture = objc_getAssociatedObject(self, &ActionHandlerTapGestureKey);
    
    if (!gesture) {
        UITapGestureRecognizer *gesture =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
        [self addGestureRecognizer:gesture];
        
        objc_setAssociatedObject(self, &ActionHandlerTapGestureKey, gesture, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        
    }
    
    objc_setAssociatedObject(self, &ActionHandlerTapGestureKey, block, OBJC_ASSOCIATION_COPY);
    
}


-(void)tap:(UITapGestureRecognizer *)tapGesture
{
    if (tapGesture.state == UIGestureRecognizerStateRecognized) {
        
        void(^action)() = objc_getAssociatedObject(self, &ActionHandlerTapGestureKey);
        
        if (action) {
            action();
        }
    }
}
@end
